
import sys, json, argparse, mergedeep
from PyQt5.QtCore import QRegExp
from PyQt5.QtGui import QTextCharFormat, QSyntaxHighlighter, QColor
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit

parser = argparse.ArgumentParser('CodeEditor')
parser.add_argument('--syntax')
parser.add_argument('--syntax-data', default='syntaxData.json')
args = parser.parse_args()

class SyntaxHighlighter(QSyntaxHighlighter):
    def __init__(self, syntaxData, parent=None):
        super(SyntaxHighlighter, self).__init__(parent)

        self.highlight_colors = {color: QColor(syntaxData['colors'][color]) for color in syntaxData['colors']}
        self.highlight_rules = [(QRegExp(syntaxData['patterns'][pattern]['pattern']), self.highlight_colors[syntaxData['patterns'][pattern]['color']]) for pattern in syntaxData['patterns']]

    def create_format(self, color):
        char_format = QTextCharFormat()
        char_format.setForeground(color)
        return char_format

    def highlightBlock(self, text):
        for pattern, char_format in self.highlight_rules:
            expression = QRegExp(pattern)
            index = expression.indexIn(text)

            while index >= 0:
                length = expression.matchedLength()
                self.setFormat(index, length, char_format)
                index = expression.indexIn(text, index + length)

class CodeEditor(QTextEdit):
    def __init__(self, parent=None):
        super(CodeEditor, self).__init__(parent)
        self.highlighter = SyntaxHighlighter(syntaxData, self.document())

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        central_widget = CodeEditor(self)
        self.setCentralWidget(central_widget)

        self.setGeometry(100, 100, 800, 600)
        self.setWindowTitle('Code Editor')

syntaxData = {'colors':{},'patterns':{}}
if args.syntax:
    if args.syntax_data:
        selectedSyntax = args.syntax
        dependenciesLoaded = []
        dependencies = [selectedSyntax]
        with open(args.syntax_data) as f:
            syntaxDataPaths = json.load(f)
        while len(dependencies) > 0:
            with open(syntaxDataPaths[dependencies[0]]) as f:
                tempSyntaxData = json.load(f)
            for dependency in tempSyntaxData['inherits']:
                if dependency in dependenciesLoaded:
                    continue
                dependencies.append(dependency)
            mergedeep.merge(syntaxData, tempSyntaxData)
            dependencies.remove(dependencies[0])
    else:
        sys.exit()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
